<?php
class ViSeminarAccommodation_Controller extends AdminController {
    
    public function __construct() {
        parent::__construct('viSeminar');
        $this->setDefaultListOrder('begin_date', 'DESC');
    }

    function edit() {
    	$viSeminarId = $this->input->get('seminar_id');
    	
    	// Basic validation
    	if (! valid::isId($viSeminarId)) {
    		$this->redirectToList('error.invalidId');
    	}
    	
    	$viSeminar = $this->dao->getById('vi_seminar', $viSeminarId);
    	if (! $viSeminar) {
    		$this->redirectToList('error.recordNotFound');
    	}
    	
    	$this->viewData['formData'] = array(
    			'vi_seminar_id' => $viSeminar['id'],
    			'currency_code' => ViregWizardData::$CURRENCY_CODE);
    	
    	$this->loadFormData($viSeminar);
    	
    	$this->renderMySubview('viSeminarAccommodationForm');
    }
    
    function loadFormData($viSeminar) {
    	$this->viewData['accommodationOptions'] = $this->dao->queryOptions(
    			'SELECT code, name ' .
    			'FROM vi_accomodation_type at ' .
    			'WHERE code NOT IN (SELECT vi_accomodation_type_code FROM vi_seminar_accomodation_type WHERE vi_seminar_id = :vi_seminar_id) ' .
    			'ORDER BY name',
    			array('vi_seminar_id' => $viSeminar['id']));
    }
    
    function save() {
    	$formData = $this->postToDbValues();
    	
    	if (! $formData['vi_seminar_id']) {
    		$this->redirect('/admin/viSeminar/overview');
    	}
    	
    	// Basic validation
    	$validator = new EntityValidator($formData, 'viSeminarAccommodation');
    	$validator->required('vi_accomodation_type_code');
    	$validator->required('price');
    	
    	if ($this->msg->hasErrors()) {
    		$this->redirect('/admin/viSeminar/display?id=' . $formData['vi_seminar_id']);
    		return;
    	}
    	
    	// Database validation
    	$viAccomodationType = $this->dao->getByCode('vi_accomodation_type', $formData['vi_accomodation_type_code']);
		if (! $viAccomodationType) {
			$this->msg->error('error-recordNotFound');
			$this->redirect('/admin/viSeminar/display?id=' . $formData['vi_seminar_id']);
			return;
		}
    	
    	$uniqueFields = array ('vi_accomodation_type_code', 'vi_seminar_id');
    	if ($this->dao->alreadyExists('vi_seminar_accomodation_type', $uniqueFields, $formData)) {
    		$this->msg->error('error.recordAlreadyExists');
    		$this->redirect('/admin/viSeminar/display?id=' . $formData['vi_seminar_id']);
    		return;
    	}
    	
    	// Insert
    	$entity = new ViSeminarAccomodationTypeEntity($formData);
		$this->dao->insertEntity($entity);
		
		$formData['currency_code'] = 'CZK';
		$priceEntity = new ViSeminarAccomodationTypePriceEntity($formData);
		$this->dao->insertEntity($priceEntity);
		
		$this->msg->info('viSeminarAccommodation.createSuccess', $viAccomodationType['name'], format::price($formData['price'], 'CZK'));
    	$this->redirect('/admin/viSeminar/display?id=' . $formData['vi_seminar_id']);
    }
}
